using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace muxLogCleaner
{
    public partial class frmMain : Form
    {
        private string strFiltFile = "filters.txt";

        public frmMain()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog fdlgOpen = new OpenFileDialog();
            if (fdlgOpen.ShowDialog() == DialogResult.OK)
            {
                txtbxPath.Text = fdlgOpen.FileName;
            }
        }
          
        private void btnClean_Click(object sender, EventArgs e)
        {
            string strPath = txtbxPath.Text;
            string strBackupPath, strOutPath, currLine;
            if (strPath != "")
            {
                if (File.Exists(strPath))
                {

                    this.Cursor = Cursors.WaitCursor;
                    strBackupPath = Path.GetDirectoryName(strPath) + "\\" + Path.GetFileNameWithoutExtension(strPath) + "_backup.txt";
                    strOutPath = Path.ChangeExtension(strPath, "tmp");
                    File.Delete(strBackupPath);
                    File.Copy(strPath, strBackupPath);
                    File.Delete(strOutPath);
                    StreamWriter sw = new StreamWriter(strOutPath);
                    StreamReader sr = new StreamReader(strPath, System.Text.Encoding.UTF7);
                    while (!sr.EndOfStream)
                    {
                        currLine = sr.ReadLine();
                        if (!matchesFilter(currLine))
                        {
                            if (chkbxFiltEmpty.Checked)
                            {
                                sw.WriteLine(currLine.Trim());
                            }
                            else
                            {
                                sw.WriteLine(currLine);
                            }
                            if (chkbxDoubleSpace.Checked)
                            {
                                sw.WriteLine();
                            }
                        }
                    }
                    sw.Close();
                    sr.Close();
                    File.Delete(strPath);
                    File.Copy(strOutPath, strPath);
                    File.Delete(strOutPath);
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("Log cleaned!", "Log Cleaner", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("You must select a log to clean.", "Log Cleaner", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool matchesFilter(string currLine)
        {
            bool result = false;
            string strCurrFilt;
            Regex reg;

            if (currLine == "")
            {
                result = chkbxFiltEmpty.Checked;
            }
            else
            {
                for (int i = 0; i < lstbxFilt.Items.Count; i++)
                {
                    strCurrFilt = lstbxFilt.Items[i].ToString();
                    if (strCurrFilt.StartsWith("^"))
                    {
                        reg = new Regex(strCurrFilt, RegexOptions.IgnoreCase);
                    }
                    else
                    {
                        reg = new Regex(WildcardToRegex(strCurrFilt), RegexOptions.IgnoreCase);
                    }
                    if (reg.IsMatch(currLine))
                    {
                        result = true;
                        break;
                    }
                }
            }
            return result;
        }

        public static string WildcardToRegex(string pattern)
        {
            return "^" + Regex.Escape(pattern).
            Replace("\\*", ".*").
            Replace("\\?", ".") + "$";
        }

        private void btnAddFilt_Click(object sender, EventArgs e)
        {
            string newPattern;
            frmPatternAdd newPat = new frmPatternAdd();
            if (newPat.ShowDialog() == DialogResult.OK)
            {
                newPattern = newPat.NewPattern;
                lstbxFilt.Items.Add(newPattern);
            }
            SyncFilterFile(true);
        }

        private void btnDeleteFilt_Click(object sender, EventArgs e)
        {
            if (lstbxFilt.SelectedIndex != -1)
            {
                lstbxFilt.Items.Remove(lstbxFilt.Items[lstbxFilt.SelectedIndex]);
            }
            else
            {
                MessageBox.Show("You must select a filter pattern to delete before pressing the Delete Filter button.", "Log Cleaner", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SyncFilterFile(true);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            strFiltFile = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location) + "\\" + "filters.txt";
            SyncFilterFile(false);
        }

        private void SyncFilterFile(bool SaveChanges)
        {
            string currLine;
            if (File.Exists(strFiltFile))
            {
                if (SaveChanges)
                {
                    File.Delete(strFiltFile);
                    StreamWriter filtStream = new StreamWriter(strFiltFile);
                    for (int i = 0; i < lstbxFilt.Items.Count; i++)
                    {
                        filtStream.Write(lstbxFilt.Items[i].ToString() + "\n");
                    }
                    filtStream.Close();
                }
                else
                {
                    lstbxFilt.Items.Clear();
                    StreamReader filtStream = new StreamReader(strFiltFile);
                    while (!filtStream.EndOfStream)
                    {
                        currLine = filtStream.ReadLine();
                        if (currLine != "")
                        {
                            lstbxFilt.Items.Add(currLine);
                        }
                    }
                    filtStream.Close();
                }
            }
            else
            {
                StreamWriter filtStream = new StreamWriter(strFiltFile);
                for (int i = 0; i < lstbxFilt.Items.Count; i++)
                {
                    filtStream.Write(lstbxFilt.Items[i].ToString() + "\n");
                }
                filtStream.Close();
            }
        }

        private void stripMTriggers()
        {
            string tmpIn = "C:\\Documents and Settings\\Allen Anselmo\\Desktop\\Devilshire Mathias triggers.mct";
            string tmpOut = "C:\\Documents and Settings\\Allen Anselmo\\Desktop\\MathiasTriggers.txt";
            StreamReader sr = new StreamReader(tmpIn);
            StreamWriter sw = new StreamWriter(tmpOut);
            while (!sr.EndOfStream)
            {
                string currline = sr.ReadLine();
                if (currline.Contains("match="))
                {
                    sw.WriteLine(currline);
                }
            }
            sr.Close();
            sw.Close();
        }
    }
}